 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Android
 * Package  : net.solosky.easyavatar.utils
 * File     : DbPersist.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : 2011-11-11
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.utils;

import net.solosky.easyavatar.bean.AuthInfo;
import net.solosky.easyavatar.utils.Tables.AuthInfoTable;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * 
 * db操作的辅助类 
 *
 * @author solosky <solosky772@qq.com>
 *
 */
public class DbPersist {
	private static final String TAG = "DBPersist";
	private static final String DB_NAME = "easyavatar.db";
	private static final int DB_VERSION = 2;	
	 
	private final DatabaseHelper mOpenHelper;
	private static Context mContext;
	private final SQLiteDatabase dbW;			
	
	private static class DatabaseHelper extends SQLiteOpenHelper{
		DatabaseHelper(Context context){
			super(context, DB_NAME, null, DB_VERSION);
			mContext = context;
		}
 
		@Override
		public void onCreate(SQLiteDatabase db) {
			Log.w(TAG, "Creating database and tables...");
			
			//providerAuth表
			String sql = "CREATE TABLE " + AuthInfoTable.TABLE_NAME + " ("
            + AuthInfoTable.AUTH_ID+" INTEGER PRIMARY KEY,"
            + AuthInfoTable.CODE +" varchar(10),"            
            + AuthInfoTable.USERNAME +" varchar(20),"
            + AuthInfoTable.PASSWORD+" varchar(20),"
            + AuthInfoTable.IS_AUTO_LOGIN +" int(1),"
            + AuthInfoTable.TOKEN +" varchar(50),"
            + AuthInfoTable.SECRET +" varchar(50),"
            + AuthInfoTable.IS_AUTHORIZED +" int(1),"
            + AuthInfoTable.EXPIRED+" int(1)"
            + ");";
			db.execSQL(sql);
			
			//db.close();
			Log.w(TAG, "Created all tables.");
			
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			//db.close();
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
		}
		
	}
	
	public DbPersist(Context ctx){
		DbPersist.mContext = ctx;
		mOpenHelper = new DatabaseHelper(mContext);
		dbW = mOpenHelper.getWritableDatabase();	
	}
	
	/**
	 * 根据接口代码查找用户保存的验证信息
	 * @param code
	 * @return
	 */
	public AuthInfo queryAuthInfo(String code){
		String [] columns = {
				AuthInfoTable.AUTH_ID,
				AuthInfoTable.CODE,
				AuthInfoTable.USERNAME,
				AuthInfoTable.PASSWORD,
				AuthInfoTable.IS_AUTO_LOGIN,
				AuthInfoTable.TOKEN,
				AuthInfoTable.SECRET,
				AuthInfoTable.IS_AUTHORIZED,
				AuthInfoTable.EXPIRED
		};
		String selection = AuthInfoTable.CODE +" = ?";
		String[] selectionArgs = {code};
		Cursor cur = dbW.query(AuthInfoTable.TABLE_NAME, columns, selection, selectionArgs, null, null, null);
		
		if(cur.getCount()>=1){
			cur.moveToFirst();
			
			AuthInfo info = new AuthInfo();
			info.setId(cur.getInt(0));
			info.setCode(cur.getString(1));
			info.setUsername(cur.getString(2));
			info.setPassword(cur.getString(3));
			info.setAutoLogin(cur.getInt(4)==1);
			info.setToken(cur.getString(5));
			info.setSecret(cur.getString(6));
			info.setAuthorized(cur.getInt(7)==1);
			info.setExpired(cur.getLong(8));
			
			cur.close();
			return info;
		}else{
			cur.close();
			return null;
		}
	}
	
	/***
	 * 插入或者更新一条验证记录
	 * @param authInfo
	 */
	public long saveAuthInfo(AuthInfo authInfo){
		ContentValues cv = new ContentValues();
		cv.put(AuthInfoTable.CODE, authInfo.getCode());
		cv.put(AuthInfoTable.USERNAME, authInfo.getUsername());
		cv.put(AuthInfoTable.PASSWORD, authInfo.getPassword());
		cv.put(AuthInfoTable.IS_AUTO_LOGIN, authInfo.isAutoLogin());
		cv.put(AuthInfoTable.TOKEN, authInfo.getToken());
		cv.put(AuthInfoTable.SECRET, authInfo.getSecret());
		cv.put(AuthInfoTable.IS_AUTHORIZED, authInfo.isAuthorized());
		cv.put(AuthInfoTable.EXPIRED, authInfo.getExpired());
		if(authInfo.getId()==null){
			long insertId = dbW.insert(AuthInfoTable.TABLE_NAME, null, cv);
			authInfo.setId((int) insertId);
			return insertId;
		}else{
			String [] args= {authInfo.getId()+""};
			return dbW.update(AuthInfoTable.TABLE_NAME, cv, AuthInfoTable.AUTH_ID+"=?", args);
		}
	}
	
	public void close(){
		if(dbW.isOpen()) {
			dbW.close();
		}		
		mOpenHelper.close();
	}
	
	
	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		close();
	}

}

